import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/http/index.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/utils/js_channel_operation.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class ApiProtocol extends CommonApi {
  ApiProtocol.privacy() : super('privacy');
  ApiProtocol.protocol() : super('protocol');
}

class PrivacyLogic extends HtmlStringWebBaseLogic {
  @override
  String getTitle() => '隐私政策';
}

class ProtocolLogic extends HtmlStringWebBaseLogic {
  @override
  String getTitle() => '用户协议';
}

abstract class HtmlStringWebBaseLogic extends GetxController {
  WebViewController? controller;

  var progressValue = 0.obs;

  String htmlString = '';

  String getTitle();

  void init() {
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..setNavigationDelegate(
        NavigationDelegate(onProgress: (int progress) => progressValue.value = progress),
      )
      ..loadHtmlString(htmlString);
    update();
  }

  @override
  void onReady() {
    super.onReady();
    init();
  }
}

class WebH5Logic extends GetxController {
  WebViewController? controller;

  WebH5Logic(this.url, this.needParam);

  final String url;
  final bool needParam;

  String title = '';

  var progressValue = 0.obs;
  bool canGoBack = false;

  Timer? _timer;

  Future<String> _getParamString() async {
    List<String> lists = [];
    (await CoreNetBuilder.params).forEach((key, value) {
      String kv = '$key=$value';
      lists.add(kv);
    });
    return lists.appendByCharacter('&');
  }

  void init() {
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) => progressValue.value = progress,
          onPageFinished: _onPageFinished,
        ),
      )
      ..addJavaScriptChannel(
        'startFunction',
        onMessageReceived: JsChannelOperation.onMessageReceived,
      );
  }

  @override
  void onReady() async {
    super.onReady();
    init();

    String params = await _getParamString();
    String resultUrl = '$url$params&key=${XydUserService.key}&kefu=${XydUserService.kefu}';

    await controller?.loadRequest(Uri.parse(needParam ? resultUrl : url));

    update();
  }

  @override
  void onClose() {
    super.onClose();
    _timer?.cancel();
    _timer = null;
  }

  ///使用Timer更新标题
  void _onPageFinished(String url) {
    _timer = Timer.periodic(const Duration(milliseconds: 500), (timer) async {
      _timer = timer;
      await _getTitle();
      await _updateCanGoBack();
      update();
      // print(url);
    });
  }

  ///获取标题
  Future _getTitle() async {
    String title = await controller?.getTitle() ?? '';
    if (title.notEmpty) this.title = title;
  }

  Future _updateCanGoBack() async {
    canGoBack = await controller?.canGoBack() ?? false;
  }
}
